"""
性能基准测试
比较 Python OpenCV 和 Rust 扩展的性能
"""
import time
import cv2
import numpy as np
from pathlib import Path


def benchmark_blur_detection_opencv(image_path: str, iterations: int = 100):
    """使用OpenCV计算清晰度的基准测试"""
    img = cv2.imread(image_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    start = time.time()
    for _ in range(iterations):
        blur_score = cv2.Laplacian(gray, cv2.CV_64F).var()
    elapsed = time.time() - start
    
    return elapsed, blur_score


def benchmark_blur_detection_rust(image_bytes: bytes, iterations: int = 100):
    """使用Rust扩展计算清晰度的基准测试"""
    try:
        import face_quality_rust
        
        start = time.time()
        for _ in range(iterations):
            blur_score = face_quality_rust.calculate_blur_score(image_bytes)
        elapsed = time.time() - start
        
        return elapsed, blur_score
    except ImportError:
        print("⚠️  Rust扩展未安装，跳过Rust基准测试")
        return None, None


def benchmark_batch_processing(image_bytes: bytes, iterations: int = 100):
    """批量处理基准测试"""
    try:
        import face_quality_rust
        
        start = time.time()
        for _ in range(iterations):
            metrics = face_quality_rust.calculate_quality_metrics(image_bytes)
        elapsed = time.time() - start
        
        return elapsed, metrics
    except ImportError:
        return None, None


if __name__ == "__main__":
    import sys
    
    if len(sys.argv) < 2:
        print("用法: python examples/benchmark.py <image_path>")
        sys.exit(1)
    
    image_path = sys.argv[1]
    if not Path(image_path).exists():
        print(f"❌ 图片不存在: {image_path}")
        sys.exit(1)
    
    print("=" * 70)
    print("🚀 性能基准测试")
    print("=" * 70)
    print(f"📷 测试图片: {image_path}")
    print(f"🔄 迭代次数: 100")
    print()
    
    # 读取图片字节
    with open(image_path, "rb") as f:
        image_bytes = f.read()
    
    # OpenCV 基准测试
    print("🐍 测试 Python OpenCV...")
    opencv_time, opencv_score = benchmark_blur_detection_opencv(image_path)
    print(f"   耗时: {opencv_time:.3f}秒")
    print(f"   清晰度: {opencv_score:.2f}")
    print()
    
    # Rust 基准测试
    print("🦀 测试 Rust 扩展...")
    rust_time, rust_score = benchmark_blur_detection_rust(image_bytes)
    if rust_time is not None:
        print(f"   耗时: {rust_time:.3f}秒")
        print(f"   清晰度: {rust_score:.2f}")
        print()
        
        speedup = opencv_time / rust_time
        print("📊 性能对比:")
        print(f"   Rust 加速比: {speedup:.2f}x")
        print(f"   性能提升: {(speedup - 1) * 100:.1f}%")
        print()
    else:
        print("   ⚠️  Rust扩展未安装")
        print("   💡 安装方法: cd rust_extension && bash build.sh")
        print()
    
    # 批量处理测试
    print("📦 测试批量处理...")
    batch_time, metrics = benchmark_batch_processing(image_bytes)
    if batch_time is not None:
        blur, contrast, brightness = metrics
        print(f"   耗时: {batch_time:.3f}秒")
        print(f"   清晰度: {blur:.2f}")
        print(f"   对比度: {contrast:.2f}")
        print(f"   亮度: {brightness:.2f}")
    print()
    
    print("=" * 70)
    print("✅ 基准测试完成")
    print("=" * 70)

